<template>
  <view class="page-container">
    <!-- 自定义Header -->
    <CustomHeader></CustomHeader>
    
    <!-- 页头 -->
    <view class="header-nav">
      <view class="back-btn" @click="goBack">
        <image class="back-icon" src="/static/icons/candidate/pre_page.png"></image>
      </view>
      <view class="header-title">选择职位</view>
      <view class="header-right"></view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <scroll-view
        class="content-scroll"
        scroll-y
        @scrolltolower="onScrollToLower"
        lower-threshold="50"
        :style="{ height: scrollViewHeight + 'px' }"
      >
        <!-- 加载中提示 -->
        <view
          v-if="loading && positionList.length === 0"
          class="loading-wrapper"
        >
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 职位列表 -->
        <view class="position-list" v-else-if="positionList.length > 0">
          <view
            class="position-item"
            v-for="position in positionList"
            :key="position.id"
            :class="{ 'selected': selectedPosition && selectedPosition.id === position.id }"
            @click="selectPosition(position)"
          >
            <view class="position-header">
              <view class="position-title">
                <text class="position-name">{{ position.jobName }}</text>
                <view
                  class="position-status"
                  :style="{ color: getStatusColor(position.status) }"
                >
                  <text class="status-text">{{ getStatusText(position.status) }}</text>
                </view>
              </view>
              <view class="position-salary">
                <text class="salary-text">{{ formatSalary(position) }}</text>
              </view>
            </view>

            <view class="position-info">
              <view class="info-item">
                <text class="info-text">经验要求：{{ position.expYears }}</text>
              </view>
              <view class="info-item">
                <text class="info-text">学历要求：{{ position.edu }}</text>
              </view>
              <view class="info-item">
                <text class="info-text">工作地点：{{ position.city }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-else-if="!loading">
          <text class="empty-text">暂无职位数据</text>
        </view>

        <!-- 加载更多 -->
        <view v-if="loadingMore" class="load-more">
          <text class="load-text">加载中...</text>
        </view>

        <!-- 已到底部 -->
        <view v-else-if="!hasMore && positionList.length > 0" class="no-more">
          <text class="no-more-text">已经到底了</text>
        </view>
      </scroll-view>
    </view>

    <!-- 底部确认按钮 -->
    <view class="fixed-bottom">
      <button 
        class="confirm-btn" 
        @click="confirmSelection"
        :disabled="!selectedPosition"
      >
        确认选择
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import CustomHeader from "@/components/CustomHeader.vue"
import { getHrJobListApi } from '@/api/position.js'

// 职位列表数据
const positionList = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(0)
const totals = ref(0)
const scrollViewHeight = ref(500)

// 选中的职位
const selectedPosition = ref(null)

// 页面参数
const candidateName = ref('')
const candidateId = ref('')
const sessionId = ref('')

// 页面加载
onLoad((options) => {
  console.log('职位选择页面参数:', options)
  
  candidateName.value = decodeURIComponent(options.candidateName || '候选人')
  candidateId.value = options.candidateId || ''
  sessionId.value = options.sessionId || ''
  
  // 计算scroll-view高度
  calculateScrollHeight()
  
  // 获取职位列表
  getPositionList(true)
})

// 获取职位列表
const getPositionList = async (isRefresh = false) => {
  console.log('获取职位列表 - isRefresh:', isRefresh, 'currentPage:', currentPage.value)

  if (loading.value && !isRefresh) {
    console.log('正在加载中，跳过')
    return
  }
  if (loadingMore.value && isRefresh) {
    console.log('正在加载更多，跳过刷新')
    return
  }

  try {
    if (isRefresh) {
      currentPage.value = 1
      loading.value = true
      positionList.value = [] // 清空列表
      console.log('刷新模式 - 清空列表，重置页码')
    } else {
      if (!hasMore.value) {
        console.log('无更多数据可加载')
        return
      }
      loadingMore.value = true
      console.log('加载更多模式 - 页码:', currentPage.value)
    }

    const params = {
      pageNo: isRefresh ? 1 : currentPage.value,
      pageSize: pageSize.value,
      status: 1 // 只获取开启状态的职位
    }

    console.log('请求参数:', params)
    const response = await getHrJobListApi(params)
    console.log('职位列表响应:', response)

    if (response) {
      totalPages.value = response.totalPages || 0
      totals.value = response.totals || 0

      console.log(
        '响应数据 - totalPages:',
        totalPages.value,
        'totals:',
        totals.value,
        'list.length:',
        (response.list || []).length
      )

      if (isRefresh) {
        positionList.value = response.list || []
        currentPage.value = 1
        console.log('刷新完成 - 当前列表长度:', positionList.value.length)
      } else {
        positionList.value.push(...(response.list || []))
        console.log('加载更多完成 - 当前列表长度:', positionList.value.length)
      }

      // 判断是否还有更多数据
      hasMore.value = currentPage.value < totalPages.value
      console.log(
        '分页状态 - hasMore:',
        hasMore.value,
        'currentPage:',
        currentPage.value,
        'totalPages:',
        totalPages.value
      )
    } else {
      console.error('响应数据为空')
    }
  } catch (error) {
    console.error('获取职位列表失败:', error)
    uni.showToast({
      title: '获取职位列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    loadingMore.value = false
    console.log(
      '请求结束 - loading:',
      loading.value,
      'loadingMore:',
      loadingMore.value
    )
  }
}

// 上拉加载更多
const onLoadMore = () => {
  console.log(
    '上拉加载更多 - currentPage:',
    currentPage.value,
    'totalPages:',
    totalPages.value
  )

  if (loadingMore.value || !hasMore.value) {
    console.log('已在加载中或无更多数据')
    return
  }

  const nextPage = currentPage.value + 1
  if (nextPage > totalPages.value) {
    console.log('已达最后一页')
    hasMore.value = false
    return
  }

  currentPage.value = nextPage
  getPositionList(false)
}

// 滚动到底部加载更多
const onScrollToLower = () => {
  console.log('滚动到底部 - 触发加载更多')
  onLoadMore()
}

// 计算scroll-view高度
const calculateScrollHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  console.log('系统信息:', systemInfo)

  // 计算可用高度：屏幕高度 - 状态栏 - header - 底部按钮 - 安全区域
  let availableHeight = systemInfo.windowHeight

  // uni.upx2px() 转换rpx到px
  const headerHeight = uni.upx2px(88 + 40) // header + padding
  const bottomHeight = uni.upx2px(100) // 底部按钮高度

  availableHeight = availableHeight - headerHeight - bottomHeight

  // 添加安全区域底部高度
  const safeAreaBottom = systemInfo.safeAreaInsets?.bottom || 0
  availableHeight -= safeAreaBottom

  scrollViewHeight.value = Math.max(availableHeight, 300) // 最小高度300px
  console.log(
    '计算的scroll-view高度:',
    scrollViewHeight.value,
    '原始窗口高度:',
    systemInfo.windowHeight
  )
}

// 格式化薪资显示
const formatSalary = (job) => {
  if (job.beginSalary && job.endSalary && job.monthlySalary) {
    return `${job.beginSalary}-${job.endSalary}K·${job.monthlySalary}个月`
  }
  return '面议'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '招聘中',
    2: '已关闭',
    3: '违规删除'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 1:
      return '#00bdb4' // 招聘中 - 绿色
    case 2:
      return '#999999' // 已关闭 - 灰色
    case 3:
      return '#ff4d4f' // 违规删除 - 红色
    default:
      return '#999999'
  }
}

// 选择职位
const selectPosition = (position) => {
  selectedPosition.value = position
  console.log('选择职位:', position)
}

// 确认选择
const confirmSelection = () => {
  if (!selectedPosition.value) {
    uni.showToast({
      title: '请选择一个职位',
      icon: 'none'
    })
    return
  }

  // 将选择的职位存储到本地存储
  uni.setStorageSync('selectedPosition', selectedPosition.value)
  
  // 返回上一页
  uni.navigateBack()
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.header-right {
  width: 60rpx;
}

/* 内容区域样式 */
.content {
  flex: 1;
  background-color: #f8f8f8;
  overflow: hidden;
  position: relative;
}

.content-scroll {
  width: 100%;
  box-sizing: border-box;
  position: relative;
}

.position-list {
  padding: 20rpx;
}

.position-item {
  background-color: #ffffff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2rpx solid transparent;

  &:active {
    background-color: #f8f8f8;
  }

  &.selected {
    border-color: #54cbc4;
    background-color: #e6f7f6;
  }
}

.position-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.position-title {
  flex: 1;
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.position-name {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  margin-right: 20rpx;
}

.position-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  background-color: rgba(0, 189, 180, 0.1);
}

.status-text {
  font-size: 24rpx;
  font-weight: 500;
}

.position-salary {
  text-align: right;
}

.salary-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #ff6b35;
}

.position-info {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-text {
  font-size: 28rpx;
  color: #666666;
}

/* 状态样式 */
.loading-wrapper,
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.loading-text,
.empty-text {
  font-size: 28rpx;
  color: #999999;
}

.load-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.load-text {
  font-size: 28rpx;
  color: #999999;
}

.no-more-text {
  font-size: 28rpx;
  color: #cccccc;
}

/* 底部确认按钮 */
.fixed-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #ffffff;
  border-top: 1rpx solid #f0f0f0;
  z-index: 100;
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  background-color: #54cbc4;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 44rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.confirm-btn[disabled] {
  background-color: #cccccc;
  color: #ffffff;
}
</style>
